(function() {

  var print = {
    init: function() {
      var self = this
      hlSelectUi()
      self.getProjectMes()
      self.exportPDF()
    },
    legalProjectName: '', // 法定项目名
    projectName: '', // 项目名
    rentPriceUnit: 'D', // 租赁价格单位
    // 获取项目信息
    getProjectMes: function() {
      var projectId = window.localStorage.getItem('PROJECTID'),
        self = this;

      hlhttp.get({
        url: 'project',
        data: {
          project_id: projectId
        },
        success: function(data) {
          if (data.legalName) {
            self.legalProjectName = data.legalName
          }
          if (data.name) {
            self.projectName = data.name
          }
          if (data.pcompany) {
            $('.pt-company-name').text(data.pcompany)
          } else {
            $('.pt-company-name').text(data.name)
          }
          // 自动显示当天日期
          var curDate = hlDateUtil.formatUTCDate(new Date().getTime(), 'yyyy-MM-dd')
          $('.date').text(curDate)


          // 账户信息
          if (data.pcompany) {
            $('.bill-name').text(data.pcompany)
          } else {
            $('.bill-name').html('--')
          }
          // 开户行和其账号
          var oldbankNameArr = []; // 开户行中文名
          var oldaccountsArr = []; // 账号

          if (data.bankAccounts) {
            var arr = data.bankAccounts.split(',')
            for (var i = 0; len = arr.length, i < len; i++) {
              oldaccountsArr.push(arr[i])
            }
            $('#account-st ul').html(self.renderList(oldaccountsArr))
          } else {
            $('#accout-st-container').text('--')
          }

          if (data.bankNames) {
            oldbankNameArr = data.bankNames.split(',')
          }
          // 因为账号、开户行中文、开户行英文三者需要对应匹配
          // 对后台的数据重新处理  达到三者一一对应关系
          var newbankNameArr = []; // 开户行中文名
          var newaccountsArr = []; // 账号
          for (var i = 0; i < oldaccountsArr.length; i++) {
            if (oldaccountsArr[i]) {
              newaccountsArr[i] = oldaccountsArr[i]
              newbankNameArr[i] = oldbankNameArr[i]
            }
          }
          self.collectionLinkage(newaccountsArr, newbankNameArr)
          self.getContractMes()
        }
      })
    },
    // 获取合同信息
    getContractMes: function() {
      var self = this,
        contractId = hlUrlUtil.GetQueryString('aid');

      hlhttp.get({
        url: 'contract',
        data: {
          id: contractId
        },
        success: function(data) {
          self.rentPriceUnit = data.rentPriceUnit;
          // 合同总面积
          var contractMes = {
            acreage: data.rentAcreage,
            rentPrice: data.rentPrice,
            beginDate: data.beginDate,
            endDate: data.endDate,
            expenses: data.expenses
          }
          $('.total-area').text(data.rentAcreage)
          if (data.zlfCompany) {
            $('.owner').text(data.zlfCompany)
          }

          // 单元号显示  如果有法定项目名  则显示法定项目名  没有显示项目名
          var unitArr = [];
          data.units.map(function(item) {
            var flag = true
            for (var i = 0; i < unitArr.length; i++) {
              if (unitArr[i].buildingName == item.buildingName && unitArr[i].floorNum == item.floorNum) {
                // 将单元添加到原有的项中  若为车位单元或者工位单元需要显示工位或者车位的个数
                var obj = {};
                if (item.unitType == 'ST') {
                  obj = {
                    buildingName: unitArr[i].buildingName,
                    floorNum: item.floorName,
                    unitName: unitArr[i].unitName + '、' + item.unitName + ' 车位' + item.positions.length + '个'
                  }
                }
                if (item.unitType == 'WP') {
                  obj = {
                    buildingName: unitArr[i].buildingName,
                    floorNum: item.floorName,
                    unitName: unitArr[i].unitName + '、' + item.unitName + ' 工位' + item.positions.length + '个'
                  }
                }
                if (item.unitType == 'BU') {
                  obj = {
                    buildingName: unitArr[i].buildingName,
                    floorNum: item.floorName,
                    unitName: unitArr[i].unitName + '、' + item.unitName
                  }
                }

                unitArr[i] = obj
                flag = false
                break;
              }
            }

            if (flag) {
              if (item.unitType == 'ST') {
                unitArr.push({
                  buildingName: item.buildingName,
                  floorNum: item.floorName,
                  unitName: item.unitName + ' 车位' + item.positions.length + '个'
                })
              }
              if (item.unitType == 'WP') {
                unitArr.push({
                  buildingName: item.buildingName,
                  floorNum: item.floorName,
                  unitName: item.unitName + ' 工位' + item.positions.length + '个'
                })
              }
              if (item.unitType == 'BU') {
                unitArr.push({
                  buildingName: item.buildingName,
                  floorNum: item.floorName,
                  unitName: item.unitName
                })
              }
            }
          })

          var unitzw = '';
          unitArr.map(function(item) {
            unitzw += item.buildingName + ' ' + (item.floorNum || '--') + ' ' + item.unitName + ','
          })
          unitzw = hlNumberUtil.deleteSybmolAtEndOfString(unitzw)

          if (self.legalProjectName) {
            unitzw = self.legalProjectName + unitzw
          } else {
            unitzw = data.projectName + unitzw
          }
          $('.zw-unit').text(unitzw)

          self.getAccountsMes(contractMes)
          self.print()
        }
      })
    },
    // 收款账号联动
    collectionLinkage: function(accountsArr, bankNameArr) {
      $(document).on('click', '#account-st li', function() {
        var index = $('#account-st li').index($(this))
        $('.account').text(accountsArr[index])

        if (bankNameArr[index]) {
          $('.openingbank').text(bankNameArr[index])
        } else {
          $('.openingbank').text('--')
        }

      })
      $($('#account-st li')[0]).click()
    },
    // 列表数据渲染
    renderList: function(data) {
      var html = ''
      data.map(function(item) {
        if (item) {
          html += '<li data-value="' + item + '">' + item + '</li>'
        }
      })
      return html
    },
    // 获取缴费信息
    getAccountsMes: function(contractMes) {
      var accountId = hlUrlUtil.GetQueryString('id'),
        self = this

      hlhttp.get({
        url: 'bill,expenses,transactions',
        data: {
          bill_id: accountId
        },
        success: function(data) {
          // 截止日期
          $('.end-time').text(hlDateUtil.formatUTCDate(data.deadlineDate, 'yyyy-MM-dd'))
          // 缴费信息
          $('.pt-tb-container').html(self.dom.paymentTable(data, contractMes))
          // 合计
          var totalPrice = 0;
          data.expenses.map(function(item) {
            totalPrice += Number(item.amountTPay)
          })

          $('.total-price').text('￥' + hlNumberUtil.formatNum(Number(totalPrice).toFixed(2)))
          self.inputText()
        }
      })
    },
    //input li
    inputText: function() {
      var oinput;
      $('.pt-table').on('focus', 'li', function(event) {
        oinput = $(this).text()
      });
      $('.pt-table').on('blur', 'li', function(event) {
        if ($(this).text() == '') {
          $(this).text(oinput)
        }
      });
    },
    // 打印
    print: function() {
      $(document).on('click', '.pt-btn', function() {
        // 打印处理前dom存储
        var bdhtml = window.document.body.innerHTML;
        // 多选项样式处理
        if ($('#openingbank-e-st').length) {
          $('.openingbank-e').html($('#openingbank-e-st').find('span').text())
        }
        if ($('#openingbank-st').length) {
          $('.openingbank').html($('#openingbank-st').find('span').text())
        }
        if ($('#account-e-st').length) {
          $('.account-e').html($('#account-e-st').find('span').text())
        }
        if ($('#account-st').length) {
          $('.account').html($('#account-st').find('span').text())
        }
        $('.pt-select-item').removeClass('pt-margin')

        var prnhtml = $('#print-area').html()
        window.document.body.innerHTML = prnhtml;
        window.print();
        window.document.body.innerHTML = bdhtml;
      })
    },
    // 导出PDF
    exportPDF: function() {
      var doctypeHtml = '<!DOCTYPE html>' +
            '<html lang="en">' +
            '<head>' +
              '<meta charset="UTF-8"></meta>' +
              '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/libs/bootstrap_3.3.7.css"></link>' +
              '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/libs/font.css"></link>' +
              '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/app/blue/blue.min.css"></link>' +
            '</head>'+
            '<body>'

      $(document).on('click', '.export-btn', function() {
        var ctxHtml = $('#print-area').html()
        var modelHtml = doctypeHtml + ctxHtml + '</body></html>'

        $.ajax({
          url:convert2pdfApi,
          type: 'post',
          data:{'html_str':modelHtml},
          headers:{token:Cookies.get("token")},
          success:function(data){
            window.open(data.url)
          }
        })
      })
    },
    dom: {
      paymentTable: function(accountMes, contractMes) {
        var html = '';
        accountMes.expenses.map(function(item) {

          // 费项价格为0时不显示该条费项
          if (item.amountTPay == 0) {
            return true
          }
          var zwName = '--';
          var egName = '';
          var expensePrice = '--';
          var acreage = '--'

          if (item.name) {
            zwName = item.name
          }

          // 费项为固定租金：**元／平米／天 ； 周期性费项：**元／月
          if (item.expenseType === 'R') {
            if(print.rentPriceUnit == 'D'){
              expensePrice = hlNumberUtil.formatNum(contractMes.rentPrice) + '元／平米／天'
            }else{
              expensePrice = hlNumberUtil.formatNum(contractMes.rentPrice) + '元／平米／月'
            }

            acreage = contractMes.acreage + '平方米'
          }
          if (item.expenseType === 'P') {
            contractMes.expenses.map(function(_item) {
              if (_item.expenseName === item.name) {
                expensePrice = hlNumberUtil.formatNum(_item.expense) + '元／月'
              }
            })
          }

          html +=
            '<ul class="pt-tb-item pt-tb-border row">' +
            '<li class="tb-1">' +
            '<span>' + zwName + '</span>' +
            '</li>' +
            '<li class="tb-2" contenteditable="true">' + hlDateUtil.formatUTCDate(accountMes.beginDate, 'yyyy-MM-dd') + '</li>' +
            '<li class="tb-3" contenteditable="true">' + hlDateUtil.formatUTCDate(accountMes.endDate, 'yyyy-MM-dd') + '</li>' +
            '<li class="tb-4" contenteditable="true"><span class="inline-block price-wrap">' + expensePrice + '</span></li>' +
            '<li class="tb-5" contenteditable="true">' + acreage + '</li>' +
            '<li class="tb-6">￥' + hlNumberUtil.formatNum(item.amountTPay) + '</li>' +
            '</ul>'

        })
        return html
      }
    }
  }

  print.init()
}())
